#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "InetAddr.hpp"

#define SOCKET_ERROR 1
#define BIND_ERROR 2

static const uint16_t glocalport = 8888;
static const int gsockfd = -1; // 默认设置为错误的fd
using func_t = std::function<std::string(std::string)>;

class udpserver
{
public:
    udpserver(func_t func, uint16_t localport = glocalport)
        : _func(func),_sockfd(gsockfd), _localport(localport), _isrunning(false) {}

    void InitSever()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd:%d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local)); // 对本地的网络信息初始化为0
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY; // 在服务器端，ip地址任意

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
        }
        LOG(DEBUG, "bind success\n");
    }

    void Start()
    {
        _isrunning = true;
        char inbuffer[1024]; // 进行网络通信的字符
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); // socklen_t要求必须和int有相同的长度
            ssize_t n = recvfrom(_sockfd, &inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            std::cout << "process in here" << std::endl;
            if (n > 0)
            {
                InetAddr addr(peer); // 这个自定义类将端口号转为主机序列，将ip转为string点式
                inbuffer[n] = 0;

                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]#" << inbuffer << std::endl;

                std::string result=_func(inbuffer);

                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
            else
            {
                LOG(FATAL, "recvfrom error\n");
            }
        }
    }
    ~udpserver()
    {
        if (_sockfd > gsockfd)
            close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport; // uint16_t是16位整数
    bool _isrunning;
    func_t _func;
};